package com.baijiayun.liveuibase.toolbox.rollcall

import android.os.Bundle
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintSet
import androidx.core.content.ContextCompat
import com.baijiayun.livecore.models.LPRoomRollCallResultModel
import com.baijiayun.liveuibase.R
import com.baijiayun.liveuibase.base.BaseDialogFragment
import com.baijiayun.liveuibase.base.RouterListener
import com.baijiayun.liveuibase.utils.DisplayUtils
import com.baijiayun.liveuibase.utils.ThemeDataUtil
import com.baijiayun.liveuibase.utils.drawable.DrawableBuilder
import kotlinx.android.synthetic.main.uibase_dialog_roll_call_admin.*
import kotlinx.android.synthetic.main.uibase_dialog_roll_call_admin.view.ll_user_container
import kotlinx.android.synthetic.main.uibase_layout_roll_call_going.view.*
import kotlinx.android.synthetic.main.uibase_layout_roll_call_result.view.*
import kotlinx.android.synthetic.main.uibase_layout_roll_call_start.view.*

/**
 * Created by pengwenjian on 2021/1/11
 * Describe:
 */
class AdminRollCallDialogFragment : BaseDialogFragment() {
    private val checkedTextColor by lazy {
        ThemeDataUtil.getColorFromThemeConfigByAttrId(context!!, R.attr.base_theme_dialog_positive_text_color)
    }
    private val unCheckedTextColor by lazy {
        ThemeDataUtil.getColorFromThemeConfigByAttrId(context!!, R.attr.base_theme_window_main_text_color)
    }
    private val checkedDrawable by lazy {
        DrawableBuilder()
                .cornerRadius(context!!.resources.getDimensionPixelSize(R.dimen.bjy_base_common_bg_radius))
                .solidColor(ThemeDataUtil.getColorFromThemeConfigByAttrId(context!!, R.attr.base_theme_live_product_color))
                .build()
    }
    private val unCheckedDrawable by lazy {
        DrawableBuilder()
                .cornerRadius(context!!.resources.getDimensionPixelSize(R.dimen.bjy_base_common_bg_radius))
                .strokeColor(ContextCompat.getColor(context!!, R.color.base_divider_line_other))
                .strokeWidth(2)
                .build()
    }

    private val unSelectDrawable by lazy {
        val radius = context!!.resources.getDimensionPixelSize(R.dimen.bjy_base_common_bg_radius)
        DrawableBuilder()
                .cornerRadii(radius, radius, 0, 0)
                .strokeColor(ContextCompat.getColor(context!!, R.color.base_divider_line_other))
                .strokeWidth(2)
                .build()
    }

    private val selectDrawable by lazy {
        val radius = context!!.resources.getDimensionPixelSize(R.dimen.bjy_base_common_bg_radius)
        DrawableBuilder()
                .cornerRadii(radius, radius, 0, 0)
                .solidColor(ThemeDataUtil.getColorFromThemeConfigByAttrId(context!!, R.attr.base_theme_live_product_color))
                .build()
    }

    private val emptyView by lazy {
        val container = ConstraintLayout(context!!)
        val img = ImageView(context!!)
        img.id = View.generateViewId()
        img.setImageResource(R.drawable.base_ic_rollcall_empty)
        val text = TextView(context!!)
        text.id = View.generateViewId()
        text.text = getString(R.string.base_live_no_data)
        text.setTextColor(ThemeDataUtil.getColorFromThemeConfigByAttrId(context!!, R.attr.base_theme_window_assistant_text_color))
        val imgParams = ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.WRAP_CONTENT, ConstraintLayout.LayoutParams.WRAP_CONTENT)
        imgParams.topToTop = ConstraintSet.PARENT_ID
        imgParams.startToStart = ConstraintSet.PARENT_ID
        imgParams.endToEnd = ConstraintSet.PARENT_ID
        imgParams.bottomToTop = text.id
        imgParams.verticalChainStyle = ConstraintSet.CHAIN_PACKED
        val textParams = ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.WRAP_CONTENT, ConstraintLayout.LayoutParams.WRAP_CONTENT)
        textParams.bottomToBottom = ConstraintSet.PARENT_ID
        textParams.startToStart = ConstraintSet.PARENT_ID
        textParams.endToEnd = ConstraintSet.PARENT_ID
        textParams.topToBottom = img.id
        container.addView(img, imgParams)
        container.addView(text, textParams)
        container
    }

    private val container by lazy {
        view!!.ll_user_container
    }

    private var selectResultIndex = 0

    //默认选10s
    private var checkedIndex = 0
    var duration = 0
    private var routerListener: RouterListener? = null

    //点名结果
    var lpRoomRollCallResultModel: LPRoomRollCallResultModel? = null

    override fun getLayoutId() = R.layout.uibase_dialog_roll_call_admin

    override fun init(savedInstanceState: Bundle?, arguments: Bundle?) {
        // do nothing
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        hideTitleBar()
        iv_close.setOnClickListener {
            routerListener?.onDismissRollCall()
        }
        showRollCallState(routerListener?.getRollCallStatus(), duration = duration)
    }

    fun setRouterListener(routerListener: RouterListener) {
        this.routerListener = routerListener
    }

    fun showRollCallState(status: RollCallStatus?, duration: Int = 0) {
        container.removeAllViews()
        when (status) {
            RollCallStatus.None, RollCallStatus.Start -> {
                val view = View.inflate(container.context, R.layout.uibase_layout_roll_call_start, null)
                container.addView(view)
                setDefaultStyle(view)
                view.tv_10s.setOnClickListener {
                    clickRollCallTime(view, 0)
                }
                view.tv_20s.setOnClickListener {
                    clickRollCallTime(view, 1)
                }
                view.tv_30s.setOnClickListener {
                    clickRollCallTime(view, 2)
                }
                view.tv_60s.setOnClickListener {
                    clickRollCallTime(view, 3)
                }
                view.tv_confirm.setOnClickListener {
                    routerListener?.getLiveRoom()?.toolBoxVM?.startRollCall(getRollCallTime().toLong())
                }
            }
            RollCallStatus.Going -> {
                val view = View.inflate(container.context, R.layout.uibase_layout_roll_call_going, null)
                container.addView(view)
                val spannableString = SpannableString(getString(R.string.base_live_roll_call_count_down_result, duration))
                val end = if (duration >= 10) 2 else 1
                spannableString.setSpan(ForegroundColorSpan(ContextCompat.getColor(container.context, R.color.base_warning_color)), 0, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
                view.tv_countdown_tip.text = spannableString
            }
            RollCallStatus.CoolDown, RollCallStatus.End -> {
                if (lpRoomRollCallResultModel == null) {
                    return
                }
                selectResultIndex = 0
                val view = View.inflate(container.context, R.layout.uibase_layout_roll_call_result, null)
                val ackCount = lpRoomRollCallResultModel?.ackList?.size ?: 0
                val nackCount = lpRoomRollCallResultModel?.nackList?.size ?: 0
                view.tv_roll_call_ack_count.text = getString(R.string.base_live_roll_call_result_answer_count, ackCount)
                view.tv_roll_call_nack_count.text = getString(R.string.base_live_roll_call_result_not_answer_count, nackCount)
                view.tv_roll_call_nack_count.background = selectDrawable
                view.tv_roll_call_ack_count.background = unSelectDrawable
                view.tv_roll_call_nack_count.setTextColor(checkedTextColor)
                view.tv_roll_call_ack_count.setTextColor(unCheckedTextColor)
                var nAckUserView: ViewGroup? = null
                var ackUserView: ViewGroup? = null
                var emptyView: ViewGroup? = null
                if (status == RollCallStatus.CoolDown && duration != 0) {
                    view.tv_roll_call.text = getString(R.string.base_live_roll_call_again_count_down, duration)
                    view.tv_roll_call.isEnabled = false
                } else {
                    view.tv_roll_call.text = getString(R.string.base_live_roll_call_again)
                    view.tv_roll_call.isEnabled = true
                }
                view.tv_roll_call.setOnClickListener {
                    routerListener?.setRollCallStatus(RollCallStatus.Start)
                    showRollCallState(RollCallStatus.Start)
                }
                view.tv_roll_call_nack_count.setOnClickListener {
                    if (selectResultIndex == 0) {
                        return@setOnClickListener
                    }
                    selectResultIndex = 0
                    view.tv_roll_call_nack_count.background = selectDrawable
                    view.tv_roll_call_ack_count.background = unSelectDrawable
                    view.tv_roll_call_nack_count.setTextColor(checkedTextColor)
                    view.tv_roll_call_ack_count.setTextColor(unCheckedTextColor)
                    if (nAckUserView != null) {
                        nAckUserView?.visibility = View.VISIBLE
                        ackUserView?.visibility = View.GONE
                        emptyView?.visibility = View.GONE
                    } else {
                        ackUserView?.visibility = View.GONE
                        nAckUserView?.visibility = View.GONE
                        emptyView?.visibility = View.VISIBLE
                    }
                }
                view.tv_roll_call_ack_count.setOnClickListener {
                    if (selectResultIndex == 1) {
                        return@setOnClickListener
                    }
                    selectResultIndex = 1
                    view.tv_roll_call_ack_count.background = selectDrawable
                    view.tv_roll_call_nack_count.background = unSelectDrawable
                    view.tv_roll_call_nack_count.setTextColor(unCheckedTextColor)
                    view.tv_roll_call_ack_count.setTextColor(checkedTextColor)
                    if (ackUserView != null) {
                        nAckUserView?.visibility = View.GONE
                        ackUserView?.visibility = View.VISIBLE
                        emptyView?.visibility = View.GONE
                    } else {
                        nAckUserView?.visibility = View.GONE
                        ackUserView?.visibility = View.GONE
                        emptyView?.visibility = View.VISIBLE
                    }
                }
                if (nackCount != 0 || ackCount != 0) {
                    val height = if (DisplayUtils.isPad(container.context)) {
                        (DisplayUtils.getScreenHeightPixels(container.context) * 450.0 / 768).toInt()
                    } else {
                        DisplayUtils.getScreenHeightPixels(container.context) - DisplayUtils.dip2px(container.context, 100f)
                    }
                    val params = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, height)
                    container.addView(view, params)
                    view.post {
                        if (context == null) {
                            return@post
                        }
                        emptyView = addEmptyList(view.ll_user_container)
                        if (nAckUserView != null) {
                            nAckUserView?.visibility = View.VISIBLE
                            ackUserView?.visibility = View.GONE
                            emptyView?.visibility = View.GONE
                        } else {
                            ackUserView?.visibility = View.GONE
                            nAckUserView?.visibility = View.GONE
                            emptyView?.visibility = View.VISIBLE
                        }
                    }
                    nAckUserView = addUserList(lpRoomRollCallResultModel!!.nackList)
                    if (nAckUserView != null) {
                        view.ll_user_container.addView(nAckUserView, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT))
                    }
                    ackUserView = addUserList(lpRoomRollCallResultModel!!.ackList)
                    if (ackUserView != null) {
                        view.ll_user_container.addView(ackUserView, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT))
                    }
                } else {
                    container.addView(view)
                    view.post {
                        if (context == null) {
                            return@post
                        }
                        emptyView = addEmptyList(view.ll_user_container)
                    }
                }
            }
        }
    }

    private fun addEmptyList(container: ViewGroup): ViewGroup {
        val params = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (container.parent as ViewGroup).measuredHeight)
        params.gravity = Gravity.CENTER
        removeViewFromParent(emptyView)
        container.addView(emptyView, params)
        return emptyView
    }

    private fun removeViewFromParent(view: View) {
        val viewParent = view.parent ?: return
        (viewParent as ViewGroup).removeView(view)
    }

    private fun addUserList(list: List<LPRoomRollCallResultModel.User>): ViewGroup? {
        if (list.isNullOrEmpty()) {
            return null
        }
        val container = LinearLayout(context!!)
        container.orientation = LinearLayout.VERTICAL
        for (user in list) {
            val text = TextView(container.context)
            text.text = user.name
            text.setTextColor(ThemeDataUtil.getColorFromThemeConfigByAttrId(container.context, R.attr.base_theme_window_main_text_color))
            text.gravity = Gravity.CENTER
            val padding = DisplayUtils.dip2px(container.context, 4f)
            text.setPadding(0, padding, 0, padding)
            container.addView(text, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT))
        }
        return container
    }

    fun setRollCallCountDown(duration: Int, isRollCallStatusGoing: Boolean = true) {
        if (isDetached) {
            return
        }
        if (isRollCallStatusGoing) {
            val spannableString = SpannableString(getString(R.string.base_live_roll_call_count_down_result, duration))
            val end = if (duration >= 10) 2 else 1
            spannableString.setSpan(ForegroundColorSpan(ContextCompat.getColor(container.context, R.color.base_warning_color)), 0, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
            view?.tv_countdown_tip?.text = spannableString
        } else {
            if (duration == 0) {
                view?.tv_roll_call?.isEnabled = true
                view?.tv_roll_call?.text = getString(R.string.base_live_roll_call_again)
            } else {
                view?.tv_roll_call?.isEnabled = false
                view?.tv_roll_call?.text = getString(R.string.base_live_roll_call_again_count_down, duration)
            }
        }
    }

    private fun clickRollCallTime(container: View, index: Int) {
        if (checkedIndex == index) {
            return
        }
        switchCheckedRollCallTime(checkedIndex, container, false)
        switchCheckedRollCallTime(index, container)
    }

    private fun setDefaultStyle(container: View) {
        switchCheckedRollCallTime(0, container, false)
        switchCheckedRollCallTime(1, container, false)
        switchCheckedRollCallTime(2, container, false)
        switchCheckedRollCallTime(3, container, false)
        switchCheckedRollCallTime(checkedIndex, container)
    }

    private fun getRollCallTime() = when (checkedIndex) {
        0 -> 10
        1 -> 20
        2 -> 30
        3 -> 60
        else -> 10
    }

    private fun switchCheckedRollCallTime(index: Int, container: View, checked: Boolean = true) {
        val textcolor = if (checked) checkedTextColor else unCheckedTextColor
        val drawable = if (checked) checkedDrawable else unCheckedDrawable
        when (index) {
            0 -> {
                container.tv_10s.setTextColor(textcolor)
                container.tv_10s.background = drawable
            }
            1 -> {
                container.tv_20s.setTextColor(textcolor)
                container.tv_20s.background = drawable
            }
            2 -> {
                container.tv_30s.setTextColor(textcolor)
                container.tv_30s.background = drawable
            }
            3 -> {
                container.tv_60s.setTextColor(textcolor)
                container.tv_60s.background = drawable
            }
        }
        if (checked) {
            checkedIndex = index
            container.tv_roll_call_time.text = getString(R.string.base_live_roll_call_count_down_setting, getRollCallTime())
        }
    }

    override fun onStart() {
        super.onStart()
        dialog?.setCanceledOnTouchOutside(false)
        dialog?.setCancelable(false)
        dialog?.window?.setBackgroundDrawable(DrawableBuilder()
                .rectangle()
                .solidColor(ThemeDataUtil.getColorFromThemeConfigByAttrId(context, R.attr.base_theme_window_bg_color))
                .cornerRadius(resources.getDimensionPixelSize(R.dimen.bjy_base_common_bg_radius))
                .build())
    }

    override fun hasWindowAnim() = false

    override fun setWindowParams(windowParams: WindowManager.LayoutParams) {
        super.setWindowParams(windowParams)
        windowParams.width = resources.getDimensionPixelSize(R.dimen.bjy_base_live_roll_call_width)
        windowParams.height = WindowManager.LayoutParams.WRAP_CONTENT
        windowParams.gravity = Gravity.CENTER
    }
}